package com.newly.common.core.utils;

import com.newly.common.base.exception.NewlyException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @program: newly-parent
 * @remark: 响应工具类
 * @author: guan
 * @create: 2022-01-05 23:57
 */
@Component
public class ResponseUtils {

    public void download(String filePath, String filename, HttpServletResponse response) {
        File file = new File(filePath);
        if (!file.exists()) throw new NewlyException("File done not exist!");

        try {
            filename = URLEncoder.encode(filename, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("application/stream");
        response.setCharacterEncoding("utf8");
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + filename);

        byte[] buffer = new byte[1024];
        try (FileInputStream fis = new FileInputStream(file);
             BufferedInputStream bis = new BufferedInputStream(fis)) {
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
